"use client";
import {
  PageContainer,
  ProForm,
  ProFormDigit,
  ProFormProps,
  ProFormRadio,
  ProFormText,
  ProFormTreeSelect,
} from "@ant-design/pro-components";
import { useRequest } from "ahooks";
import { Button, Card, Col, Flex, message, Row, Space } from "antd";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { RollbackOutlined } from "@ant-design/icons";
import {
  addMenuApi,
  updateMenuApi,
  getMenuApi,
  getMenuTreeApi,
} from "@/lib/api/system/menu";
import { Menu } from "@/lib/api/system/menu.d";
import { useRef } from "react";
import { FormInstance } from "antd/lib";

export default function Page() {
  const { type } = useParams();
  const router = useRouter();
  const params = useSearchParams();
  const menuId = params.get("menuId");
  const parentId = params.get("parentId");
  const title = type === "add" ? "新增菜单" : "修改菜单";
  const formRef = useRef<FormInstance>(null);

  const { run: addMenu, loading: addMenuLoading } = useRequest(addMenuApi, {
    manual: true,
    onSuccess: () => {
      message.success("新增成功");
      router.back();
    },
    onError: (error: any) => {
      message.error(error.msg);
    },
  });

  const { run: updateMenu, loading: updateMenuLoading } = useRequest(
    (params) => updateMenuApi({ ...params, menuId: menuId }),
    {
      manual: true,
      onSuccess: () => {
        message.success("修改成功");
        router.back();
      },
      onError: (error: any) => {
        message.error(error.msg);
      },
    },
  );

  const span24layout = {
    labelCol: { span: 3 },
    wrapperCol: { span: 21 },
  };

  const proFormProps: ProFormProps<Menu> = {
    layout: "horizontal",
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
    loading: addMenuLoading || updateMenuLoading,
    submitter: {
      render: (_, dom) => {
        return (
          <Flex justify="center">
            <Space>{dom}</Space>
          </Flex>
        );
      },
    },
    onFinish: async (values) => {
      if (type === "add") {
        await addMenu(values);
      } else {
        await updateMenu(values);
      }
    },
    request: async () => {
      if (type === "add") {
        return {
          parentId: parentId,
        } as Menu;
      } else {
        const res = await getMenuApi(menuId as string);
        return res.data;
      }
    },
  };

  return (
    <PageContainer
      title={title}
      extra={
        <Button icon={<RollbackOutlined />} onClick={() => router.back()}>
          返回
        </Button>
      }
    >
      <Card>
        <ProForm
          {...proFormProps}
          formRef={formRef}
          className="max-w-[800px] mx-auto my-10"
        >
          <Row gutter={16}>
            <Col span={24}>
              <ProFormTreeSelect
                {...span24layout}
                name="parentId"
                label="上级菜单"
                allowClear={false}
                key="id"
                fieldProps={{
                  fieldNames: { label: "label", value: "id" },
                }}
                request={async () => {
                  const res = await getMenuTreeApi();
                  return [{ id: "0", label: "主类目", children: res.data }];
                }}
                rules={[{ required: true, message: "请选择上级菜单" }]}
              />
            </Col>
            <Col span={24}>
              <ProFormRadio.Group
                {...span24layout}
                name="menuType"
                label="菜单类型"
                initialValue="C"
                options={[
                  { label: "目录", value: "M" },
                  { label: "菜单", value: "C" },
                  { label: "按钮", value: "F" },
                ]}
              />
            </Col>
            <Col span={24}>
              <ProFormText
                {...span24layout}
                name="icon"
                tooltip="使用iconfont图标,格式为`icon-`"
                label="菜单图标"
              ></ProFormText>
            </Col>
            <Col span={12}>
              <ProFormText
                name="menuName"
                label="菜单名称"
                rules={[{ required: true, message: "请输入菜单名称" }]}
              />
            </Col>
            <Col span={12}>
              <ProFormDigit
                name="orderNum"
                label="显示排序"
                initialValue={1}
                rules={[{ required: true, message: "请输入显示排序" }]}
              />
            </Col>
            <Col span={12}>
              <ProFormRadio.Group
                name="isFrame"
                label="是否外链"
                initialValue="1"
                options={[
                  { label: "是", value: "0" },
                  { label: "否", value: "1" },
                ]}
                tooltip="选择是外链则路由地址需要以`http(s)://`开头"
              />
            </Col>
            <Col span={12}>
              <ProFormText
                name="path"
                label="路由地址"
                tooltip="访问的路由地址，如：`user/list`，`user/add`，`user/edit`"
                rules={[{ required: true, message: "请输入路由地址" }]}
              />
            </Col>
            <Col span={12}>
              <ProFormRadio.Group
                name="isShow"
                label="是否显示"
                initialValue="0"
                options={[
                  { label: "显示", value: "0" },
                  { label: "隐藏", value: "1" },
                ]}
                tooltip="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问"
              />
            </Col>
            <Col span={12}>
              <ProFormRadio.Group
                name="status"
                label="菜单状态"
                initialValue="0"
                options={[
                  { label: "正常", value: "0" },
                  { label: "停用", value: "1" },
                ]}
                tooltip="选择停用则路由将不会出现在侧边栏，也不能被访问"
              />
            </Col>
          </Row>
        </ProForm>
      </Card>
    </PageContainer>
  );
}
